<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-11-22 17:16
 *
 * Version: 2.0
 */

namespace App\Modules\Coupon\Services;


use App\Exceptions\AllValidatorException;
use App\Lib\CreateStaticNumber;
use App\Lib\Utilities;
use App\Modules\Coupon\Repositories\CouponListRepository;
use App\Modules\Coupon\Repositories\CouponRepository;
use App\Modules\Coupon\Repositories\CouponSendRepository;
use App\Modules\Live\Repositories\LiveRepository;
use App\Modules\Store\Repositories\StoreRepository;
use Flower\Core\Repository\Eloquent\BaseService;
use Illuminate\Support\Facades\Log;

class CouponService extends BaseService
{
	protected $couponRepository;
	protected $couponSendRepository;
	protected $couponListRepository;
	protected $storeRepository;
	protected $liveRepository;

	public function __construct(CouponRepository $couponRepository, CouponSendRepository $couponSendRepository, CouponListRepository $couponListRepository, StoreRepository $storeRepository, LiveRepository $liveRepository)
	{
		$this->couponRepository = $couponRepository;
		$this->couponSendRepository = $couponSendRepository;
		$this->couponListRepository = $couponListRepository;
		$this->storeRepository = $storeRepository;
		$this->liveRepository = $liveRepository;

	}


	/**
	 * 创建优惠券
	 * @param $params
	 * @return mixed
	 */
	public function create($params)
	{
		return $this->couponRepository->add($params);
	}


	/**
	 * 编辑优惠券
	 * @param $params
	 * @return mixed
	 * @throws AllValidatorException
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function edit($params)
	{
		$id = $params['coupon_id'];
		unset($params['coupon_id']);
		$this->couponRepository->isReceivedByUserOrMember($id, '编辑');
		return $this->couponRepository->edit($id, $params);
	}


	/**
	 * 删除优惠券
	 * @param $id
	 * @return int
	 * @throws AllValidatorException
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function del($id)
	{
		$this->couponRepository->isReceivedByUserOrMember($id, '删除');
		return $this->couponRepository->del($id);
	}

	/**
	 * 店长发布优惠券
	 * @param $id
	 * @return bool
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function post($id)
	{
		return $this->couponRepository->post($id);
	}


	/**
	 * 发送优惠券给消费者
	 * @param $userId
	 * @param $request
	 * @return array
	 * @throws AllValidatorException
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function postToMember($userId, $request)
	{
		$this->liveRepository->checkExist($request->live_id);
		$info = $this->couponRepository->IsExisted($request->coupon_id);
		$leaveNum = $info->createnum - $info->send_num;
		if ($leaveNum < $request->createnum) {
			return ['status' => 0, 'msg' => '您要发送的优惠券数量，大于本优惠券剩余数量' . $leaveNum . '，请您修改后，继续操作！'];
		}
		$result = $this->couponSendRepository->add($userId, $request);
		$info->send_num += $request->createnum;
		$info->save();
		return ['status' => 1, 'msg' => '优惠券发送成功', 'data' => ''];
	}


	/**
	 * 小程序端用户获取优惠券列表
	 * @param $userId
	 * @return array
	 */
	public function getCouponSendList($userId, $storeId)
	{
		$list = $this->couponSendRepository->getListByUserId($userId, $storeId);
		return ['status' => 1, 'data' => $list, 'msg' => '成功获取优惠券列表！'];
	}


	/**
	 * 小程序端用户获取店铺的优惠券列表
	 * @param $memberId
	 * @param $storeId
	 * @return array
	 */
	public function getStoreCouponList($memberId, $storeId)
	{
		$couponList = $this->couponRepository->getCouponListToMember($storeId);
		$receiveList = $this->couponListRepository->getMemberListByStoreId($storeId, $memberId);
		return compact('couponList', 'receiveList');
	}


	/**
	 * 领取优惠券
	 * @param $request
	 * @param $memberId
	 * @return array
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function addCouponList($request, $memberId)
	{
		// 判断优惠券是否存在
		$coupon = $this->couponRepository->IsExisted($request->coupon_id);
		$live_id = 0;
		// 直播
		if (!$request->source) {
			$barberCoupon = $this->couponSendRepository->isExisted($request->id);
			$live_id = $barberCoupon->live_id;
		}

		$userId = $coupon->user_id;
		// 判断用户是否领取过优惠券
		$receiveCoupon = $request->source ? $this->couponListRepository->IsExistedByCouponIdAndMemberId($request->coupon_id,$memberId) : $this->couponListRepository->IsExistedBySendIdAndMemberId($request->id, $memberId);
		$memberCouponList = $this->couponListRepository->getListByCouponId($request->coupon_id, $live_id);
		$selfCouponList = $this->couponListRepository->getMemberSelfListToday($memberId, $userId, $live_id);
		//没领取的领取
		if (!isset($receiveCoupon)) {
			// 更改优惠券张数
			$result = $request->source ? $this->couponRepository->updateSendNums($coupon->id) : $this->couponSendRepository->updateSendNums($request->id);
			if ($result['status']) {
				$flag['status'] = 0;
				// 直播抢优惠券
//				if(!$request->source){
//					$flag = $this->couponRepository->updateSendNums($result['data']);
//				}
//				// 抢优惠券记录
//				if($request->source || (!$request->source && $flag['status'])){
				$couponCode = CreateStaticNumber::makeNo('coupon');
				$info = $this->couponListRepository->add($coupon->store_id, $coupon->id, $memberId, $couponCode, $request->source, $userId, $live_id,$request->id);
				$couponInfo = $this->couponListRepository->detail($info->id);
				$selfCouponList = $this->couponListRepository->getMemberSelfListToday($memberId, $userId, $live_id);
				$memberCouponList = $this->couponListRepository->getListByCouponId($request->coupon_id, $live_id);
				return ['status' => 1, 'msg' => '领取成功！', 'data' => ['pick_up_coupon' => $couponInfo, 'other_list' => $memberCouponList, 'self_list' => $selfCouponList]];
			}
//			}
			return [
				'status' => 0, 'msg' => '优惠券已经发放完成！请期待下次活动！', 'data' => [
					'pick_up_coupon'     =>
						[], 'other_list' => $memberCouponList, 'self_list' => $selfCouponList
				]
			];
		}
		return ['status' => 0, 'msg' => '您已经领取过该优惠券，请勿重复领取！', 'data' => ['pick_up_coupon' => [], 'other_list' => $memberCouponList, 'self_list' => $selfCouponList]];
	}


	public function getReceiveMemberCouponList($storeId, $userId)
	{
		$list = $this->couponListRepository->getReceiveMemberCouponList($storeId, $userId);
		return ['status' => 1, 'msg' => '用户领取的优惠券列表！', 'data' => $list];
	}


	/**
	 * 优惠券回收成功
	 * @param $storeId
	 * @param $userId
	 * @return array
	 */
	public function getRecoveryCouponList($storeId, $userId)
	{
		$list = $this->couponSendRepository->getRecoveryCouponList($storeId, $userId);
		return ['status' => 1, 'msg' => '用户领取的优惠券列表！', 'data' => $list];
	}

	/**
	 * 小程序端 用户的优惠券列表
	 * @param $memberId
	 * @param $status
	 * @return array
	 */
	public function getMemberCouponList($memberId, $status)
	{
		$list = $this->couponListRepository->getMemberCouponListByStatus($memberId, $status);
		$list = Utilities::dealPage($list);
		$counts = $this->couponListRepository->getMemberCouponListCountsByStatus($memberId);
		$counts = empty($counts) ? null : array_column($counts, null, 'status');
		$list['counts'] = [
			'unused_count'  => isset($counts[0]) ? $counts[0]['counts'] : 0,
			'used_count'    => isset($counts[1]) ? $counts[1]['counts'] : 0,
			'expired_count' => isset($counts[2]) ? $counts[2]['counts'] : 0,
		];
		return ['status' => 1, 'msg' => '优惠券列表获取成功！', 'data' => $list];
	}


	/**
	 * app端理发师获取店铺发布的优惠券列表
	 * @param $storeId
	 * @return array
	 */
	public function getCouponSendListFromBoss($storeId, $type = 0, $isLive = true)
	{
		$list = $this->couponRepository->getCouponListToMember($storeId, $type, $isLive);
		$newList = $isLive ? $list : Utilities::dealPage($list);
		if($isLive){
			$newList = array_map(function ($v){
				$value = intval($v['createnum'] - $v['send_num']);
				$v['name'] = '剩余'.$value.'张';
				return $v;
			},$newList);
		}else{
			$items = array_map(function ($v){
				$v['discount'] = isset($v['discount']) ? $v['discount']/10 : 0;
				return $v;
			},$newList['items']);
			$newList['items'] = $items;
		}
		return ['status' => 1, 'msg' => '优惠券列表获取成功！', 'data' => $newList];
	}


	public function checkHasCouponOut($userId, $storeId, $memberId)
	{
		$isSend = $this->couponSendRepository->isSendCoupon($userId, $storeId);
		if (empty($isSend)) {
			$result = ['status' => 0, 'msg' => '理发师没发优惠券', 'data' => $isSend];
		} else {
			$count = $this->couponListRepository->findWhere(['member_id' => $memberId, 'send_id' => $isSend->id, 'source' => 0])->count();
			$result = $count ? ['status' => 0, 'msg' => '您已经领取过优惠券', 'data' => ''] : ['status' => 1, 'msg' => '理发师发送优惠券', 'data' => $isSend];
		}
		return $result;
	}


	/**
	 * 优惠券回收操作
	 * @param $userId
	 * @param $storeId
	 * @return array
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function backNoReceiveCoupon($userId, $storeId)
	{
		$this->storeRepository->isExited($storeId);
		$list = $this->couponSendRepository->getRemainListByUserIdStoreId($userId, $storeId);
		if ($list->isEmpty()) return ['status' => 1, 'msg' => '优惠券被领完，不用回收了！'];
		$total = 0;
		foreach ($list as $info) {
			if ($info->send_num < $info->createnum) {
				$info->back_num = $info->createnum - $info->send_num;
				$total += $info->back_num;
				$info->status = 2;
				$info->save();
				$this->couponRepository->backCoupon($info->coupon_id, $info->back_num);
			}
		}
		Log::info('优惠券总共回收数量为:' . $total);
		return ['status' => 1, 'msg' => '优惠券回收完成！'];
	}



	public function couponSendAndUsedList($couponId,$isUsed){
		$list = $this->couponListRepository->getDetailListByCouponId($couponId,$isUsed);
		return ['status'=>1,'msg'=>'优惠券列表使用','data'=>Utilities::dealPage($list)];
	}
}